package com.exmple.myapplication;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.preference.PreferenceManager;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;

public class FirstFragment extends Fragment {


    private TextView tvJson;
    private final String TAG = getClass().getSimpleName();
    private String fileName;
    private ActivityResultLauncher<Uri> resultLauncher;
    private ActivityResultLauncher<String> stringActivityResultLauncher;
    public static String selectPath;
    private final String KEY_STR = "selectPath";
    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
    private SharedPreferences sharedPreferences;
    private TextView textPath;

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext());
        selectPath = sharedPreferences.getString(KEY_STR, Environment.getExternalStorageDirectory().getAbsolutePath());
        stringActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.GetContent(), result -> {
            if (result.getPath().endsWith("json")) {
                Observable.create((ObservableOnSubscribe<String>) emitter -> {
                    ContentResolver contentResolver = requireContext().getContentResolver();
                    InputStream inputStream = contentResolver.openInputStream(result);
                    byte[] bytes = new byte[inputStream.available()];
                    inputStream.read(bytes);
                    inputStream.close();
                    String s
                            = new String(bytes, StandardCharsets.UTF_8);
                    emitter.onNext(s);

                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<String>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(String s) {
                                tvJson.setText(s);
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });
            } else if (result.getPath().endsWith("xls")) {
                Intent intent = new Intent("android.intent.action.VIEW");
                intent.addCategory("android.intent.category.DEFAULT");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(result, "application/vnd.ms-excel");
                requireContext().startActivity(intent);
            }
        });
        resultLauncher = registerForActivityResult(new ActivityResultContracts.OpenDocumentTree(), result -> {
            if (result == null) {
                return;
            }
            Uri uri = DocumentsContract.buildDocumentUriUsingTree(
                    result,
                    DocumentsContract.getTreeDocumentId(result)
            );
            try {
                selectPath = ReaderUtils.getImageAbsolutePath(requireContext(), uri);

            } catch (ArrayIndexOutOfBoundsException exception) {
                selectPath = Environment.getExternalStorageDirectory().getAbsolutePath();
            }
            textPath.setText(selectPath);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putString(KEY_STR, selectPath);
            edit.apply();
            Log.i(TAG, "onActivityResult: " + "\r\n" + selectPath);
        });
    }

    private void createDir(Uri result) {
        if (result == null) {
            return;
        }
        Uri uri = DocumentsContract.buildDocumentUriUsingTree(
                result,
                DocumentsContract.getTreeDocumentId(result)
        );
        Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
            ContentResolver contentResolver = requireContext().getContentResolver();
            Uri dicName = DocumentsContract.createDocument(contentResolver, uri, DocumentsContract.Document.MIME_TYPE_DIR,
                    "人来json");

           /* DocumentFile file = DocumentFile.fromTreeUri(requireContext(), result);
            if (file != null) {
                DocumentFile[] documentFiles = file.listFiles();
                for (DocumentFile file1 : documentFiles) {
                    if (!TextUtils.isEmpty(file1.getName()) && file1.getName().contains("人来json目录")) {
                        return;
                    }
                }

                DocumentFile file1 = file.createFile("text/json", "人来json目录.json");
                OutputStream outputStream = contentResolver.openOutputStream(file1.getUri());
                outputStream.write("json保存于此".getBytes());
                outputStream.flush();
                outputStream.close();
            }*/

            selectPath = ReaderUtils.getImageAbsolutePath(requireContext(), dicName);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putString(KEY_STR, selectPath);
            edit.apply();
            emitter.onNext(true);
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        textPath.setText(selectPath);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "onError: " + e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.fragment_first, null);
        Button btnSelectDir = view.findViewById(R.id.button_first_3);
        Button btnSelectFile = view.findViewById(R.id.button_first_4);
        Button btnJson = view.findViewById(R.id.button_first);
        Button btnExcel = view.findViewById(R.id.button_first_2);
        tvJson = view.findViewById(R.id.tv);
        textPath = view.findViewById(R.id.tv_path);
        btnExcel.setOnClickListener(v -> createExcel());
        btnJson.setOnClickListener(v -> createJson());
        btnSelectDir.setOnClickListener(v -> selectDir());
        btnSelectFile.setOnClickListener(v -> selectFile());
        textPath.setText(selectPath);

        return view;

    }

    public void selectFile() {
        stringActivityResultLauncher.launch("*/*");
    }

    public void selectDir() {

        resultLauncher.launch(null);
    }

    private void createJson() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("时间", simpleDateFormat.format(new Date(System.currentTimeMillis())));
            jsonObject.put("地点", "广州增城");
            jsonObject.put("公司", "人来康复");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        createJson(jsonObject, "");
    }

    public void createJson(Object o, String file_Name) {
        this.fileName = file_Name;
        Gson gson = new Gson();
        String s = gson.toJson(o);
        extractJson(s);
    }

    private void extractJson(String s) {
        Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
            if (TextUtils.isEmpty(fileName)) {
                fileName = simpleDateFormat.format(new Date(System.currentTimeMillis()));
            }
            FileOutputStream fileOutputStream = new FileOutputStream(selectPath + File.separator + fileName + ".json");
            fileOutputStream.write(s.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
            emitter.onNext(true);
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                            Toast.makeText(requireContext(), "保存成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(requireContext(), "保存失败", Toast.LENGTH_SHORT).show();

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(requireContext(), "保存失败:" + e.toString(), Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void createJson(Collection<Object> collection, String file_Name) {
        Gson gson = new Gson();
        this.fileName = file_Name;
        String s = gson.toJson(collection);
        extractJson(s);
    }

    private void createExcel() {
        createExcel("", isReady -> {
            if (isReady) {
                addExcelFloatData(new Float[]{0.1f, 0.2f, 0.3f});
                addExcelStringData(new String[]{"a", "b", "c"});
                finishExcel();

            }
        }, "1", "2", "3");
    }

    public void finishExcel() {
        ExcelUtil.getInstance().finish();
    }


    public void createExcel(String file_Name, ExcelUtil.ExcelListener listener, String... title) {
        this.fileName = file_Name;
        if (TextUtils.isEmpty(fileName)) {
            fileName = simpleDateFormat.format(new Date(System.currentTimeMillis()));
        }
        ArrayList<String> strings = new ArrayList<>(Arrays.asList(title));
//        strings.add(0,"时间");
        ExcelUtil.getInstance().setPath(selectPath).createExcel(fileName, strings, listener);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void addExcelFloatData(Float[] floats) {
        addExcelFloatData(new ArrayList<>(Arrays.asList(floats)));
    }

    public void addExcelFloatData(Collection<Float> floats) {
        ExcelUtil.getInstance().putFloatData(floats);
    }

    public void addExcelStringData(String[] strings) {
        addExcelStringData(new ArrayList<>(Arrays.asList(strings)));
    }

    public void addExcelStringData(Collection<String> strings) {
        ExcelUtil.getInstance().putStringData(strings);
    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

}